Shadowing in Rust

Metadata
aliases: [Shadowing variables in Rust]
shorthands: {}
created: 2022-01-26 23:18:00
modified: 2022-01-26 23:28:57

In Rust, when we already declared a variable with the let keyword, we can declare a new variable with the same name. Here, the second variable shadows the first one. This behavior can be demonstrated with this code:

fn main() {
    let x = 5;
    let x = x + 1;

    {
        let x = x * 2;
        println!("The value of x in the inner scope is: {}", x);
    }

    println!("The value of x is: {}", x);
}

The output of this will be:

The value of x in the inner scope is: 12
The value of x is: 6

Shadowing also works with different types:

fn main() {
    let x = 2;

    {
        let x = "something else with another type";
        println!("The value of x in the inner scope is: {}", x);
    }

    println!("The value of x is: {}", x);
}

Which results in:

The value of x in the inner scope is: something else with another type
The value of x is: 2

This behavior is different than using the mut keyword to declare the variable, since we still cannot reassign the variable with a different type. So this works:

let wordlen = "someword";
let wordlen = wordlen.len(); // Works fine

While this results in a big error:

let mut wordlen = "someword";
wordlen = wordlen.len(); // ERROR